package logic

import (
	"autotestservice/testservices/internal/data"
	"autotestservice/testservices/internal/deviceMng"
	"context"
	"gitee.com/jmdvirus/jkgo/jk/jklog"
	"math/rand"
	"strconv"
	"time"

	"autotestservice/testservices/internal/svc"
	"autotestservice/testservices/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type AutotestStartLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAutotestStartLogic(ctx context.Context, svcCtx *svc.ServiceContext) AutotestStartLogic {
	return AutotestStartLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AutotestStartLogic) AutotestStart(req types.RequestTestProjectStart) (*types.TestProjectResponse, error) {
	jklog.L().Debugln("test start")
	tp := types.TestProject{}
	res := &types.TestProjectResponse{
		Code:     0,
		Message:  "",
		TestProj: tp,
	}
	devOpt := deviceMng.NewDeviceOption(req.TestTarget.ConnectStyle, req.TestTarget.Addr, req.TestTarget.Port)
	findDev := deviceMng.GlobalDeviceMng().Find(*devOpt)
	if findDev != nil {
		// 已连接
		// TODO: 对已经 start 过的进行过滤
		rand.Seed(time.Now().UnixNano())
		iid := rand.Int63n(1000000) + 100000
		tp.Id = strconv.FormatInt(time.Now().Unix(), 10) + strconv.FormatInt(iid, 10)
		tp.Model = req.Model
		tp.DeviceId = req.DeviceId
		tp.TestUser = req.TestUser
		tpn, err := data.AutoTestTestProjectStart(tp)
		if err != nil {
			jklog.L().Errorln(err)
			res.Code = 10
			res.Message = err.Error()
		} else {
			res.Message = "success"
			res.TestProj = tpn
		}
	} else {
		res.Code = 1
		res.Message = "device not connect"
	}

	return res, nil
}
